package com.learning.platform.repository;

import com.learning.platform.entity.UserFavorite;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserFavoriteRepository extends JpaRepository<UserFavorite, Long> {
    
    /**
     * 检查用户是否已收藏课程
     */
    boolean existsByUserIdAndCourseId(Long userId, Long courseId);
    
    /**
     * 查找用户对课程的收藏记录
     */
    Optional<UserFavorite> findByUserIdAndCourseId(Long userId, Long courseId);
    
    /**
     * 获取用户的收藏列表，按时间倒序
     */
    Page<UserFavorite> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
    
    /**
     * 获取用户收藏的课程ID列表
     */
    @Query("SELECT f.courseId FROM UserFavorite f WHERE f.userId = :userId")
    List<Long> findCourseIdsByUserId(@Param("userId") Long userId);
    
    /**
     * 获取课程的收藏数量
     */
    long countByCourseId(Long courseId);
    
    /**
     * 删除课程的所有收藏记录
     */
    void deleteByCourseId(Long courseId);
}


